import React, { Component } from 'react'

import './css/index.css'

export default class App extends Component {
  state = {
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  }

  box = React.createRef()

  constructor() {
    super()
    console.log('constructor')
  }

  render() {
    return (
      <div>
        <h1>邮件</h1>
        <button
          onClick={() =>
            this.setState({
              list: [
                ...[11, 12, 13, 14, 15, 16, 17, 18, 19],
                ...this.state.list,
              ],
            })
          }
        >
          新邮件
        </button>
        <div
          style={{
            height: '200px',
            backgroundColor: 'yellow',
            overflow: 'auto',
          }}
          ref={this.box}
        >
          <ul>
            {this.state.list.map((item) => {
              return (
                <li
                  key={item}
                  style={{ height: '100px', border: '1px solid red' }}
                >
                  {item}
                </li>
              )
            })}
          </ul>
        </div>
      </div>
    )
  }

  // 替代 componentWillUpdate
  getSnapshotBeforeUpdate = (prevProps, prevState) => {
    console.log('getSnapshotBeforeUpdate', prevProps, prevState)
    return this.box.current.scrollHeight
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('componentDidUpdate', prevProps, prevState, snapshot)

    let scrollHeight = this.box.current.scrollHeight
    if (snapshot !== scrollHeight) {
      console.log(
        'componentDidUpdate',
        this.box.current.scrollTop,
        scrollHeight,
        snapshot
      )
      this.box.current.scrollTop += scrollHeight - snapshot
    }
  }

  componentDidMount() {
    console.log('componentDidMount')
  }
}
